package com.cy.web;




import com.alibaba.fastjson2.JSONObject;
import com.cy.bean.*;
import com.cy.mapper.ActivityMapper;
import com.cy.redis.CacheRedisService;
import com.cy.service.ActivityService.ActivityService;
import com.cy.service.UserService;
import com.cy.service.VipsetService;
import com.cy.tools.Bubbling;
import com.cy.tools.HttpRequest;
import com.cy.tools.Tool;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

@Controller
//@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private VipsetService vipsetService;


    @Autowired
    private CacheRedisService cacheRedisService;
    @Autowired
    private Bubbling bubbling;


    @RequestMapping("/getUserOpenId")
    @ResponseBody
    public String getUserOpenId(HttpSession session,String encryptedData, String iv, String code) throws JSONException {

        // 登录凭证不能为空
        if (code == null || code.length() == 0) {
//            map.put("status", 0);
//            map.put("msg", "code 不能为空");
            return "登录code为空";
        }

        // 小程序唯一标识 (在微信小程序管理后台获取)
        String wxspAppid = "wxe50b68560b1e9ea5";
        // 小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "a0f472eded45fb217859623b0daf0c61";
        // 授权（必填）
        String grant_type = "authorization_code";


        // 请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        // 解析相应内容（转换成json对象）
        org.json.JSONObject json = new org.json.JSONObject(sr);
        // 获取会话密钥（session_key）
//        String session_key = json.get("session_key").toString();
//        // 用户的唯一标识（openid）
        String openid = json.get("openid").toString();
        System.out.println("openid==="+openid);
        User user = userService.doLogin(openid);
        if (user != null){
            String uobj = JSONObject.toJSONString(user);
            String uid = JSONObject.toJSONString(user.getUid());
            cacheRedisService.add("uid",uid);
            return uobj;
        }else {
            User addUser = new User();
            addUser.setUopid(openid);
            addUser.setUstate("0");
            addUser.setUvip(0);
            addUser.setUcredit(0);
            addUser.setUpoint("0");
            int a = userService.addUser(addUser);
            System.out.println(a+"=========");
            User user1 = userService.doLogin(openid);
            String uobj = JSONObject.toJSONString(user1);
            String uid = JSONObject.toJSONString(user1.getUid());
            cacheRedisService.add("uid",uid);
            return uobj;
        }
    }

//    缘分列表数据
    @RequestMapping("/userList")
    @ResponseBody
    public String userList(String follow,String uid){
        Userbasicmessage userba = userService.selecUserba(Integer.parseInt(uid));
        if (follow.equals("1")){  //未关注列表
            List<Userbasicmessage> userList1 = userService.selectUser((int) userba.getUid(),userba.getUsex(), (int) userba.getUage(), userba.getUprovince());
            if (userList1 != null){
//                冒泡排序
                userList1 = bubbling.userList(userList1,Integer.parseInt(uid));
                String uobj = JSONObject.toJSONString(userList1);
//                cacheRedisService.add("userInfo",uobj);
                return uobj;
            }else {
                return "error";
            }
        }else { //已关注列表
            List<Userbasicmessage> userList2 = userService.followUser((int) userba.getUid(),userba.getUsex(), (int) userba.getUage(), userba.getUprovince());
            if (userList2 != null){

                String uobj = JSONObject.toJSONString(userList2);
                cacheRedisService.add("userInfo",uobj);
                return uobj;
            }else {
                return "error";
            }
        }
    }


//摇一摇
    @RequestMapping("/shake")
    @ResponseBody
    public String shake(HttpSession httpSession,String follow){
        System.out.println("摇一摇++++++++++");
        User user = (User) httpSession.getAttribute("user");
        Userbasicmessage userba = userService.selecUserba(1);
        List<Userbasicmessage> userList1 = userService.selectUser((int) userba.getUid(),userba.getUsex(), (int) userba.getUage(), userba.getUprovince());
        if (userList1 != null){


            httpSession.setAttribute("userList",userList1);
            String uobj = JSONObject.toJSONString(userList1.get(0));
            cacheRedisService.add("userInfo",uobj);
            return uobj;
        }else {
            return "error";
        }
    }

    //修改关注
    @RequestMapping("/updateFollow")
    @ResponseBody
    public String updateFollow(String uid,String friendid){
        System.out.println(uid+"修改++++++++++"+friendid);
        int a = userService.updateFollow(Integer.parseInt(uid),Integer.parseInt(friendid),1);
        if (a != 0 ){
            return "true";
        }else {
            return "false";
        }
    }

    //报名最新活动
    @RequestMapping("/newActivity")
    @ResponseBody
    public String newActivity(String activityid,String activityspend){
        System.out.println("最新活动+++++++++"+activityid +"---"+ activityspend);
        List<Activity>  activityList = activityService.selectActivity();
        if (activityList != null ){
            String activitys = JSONObject.toJSONString(activityList);
            return activitys;
        }else {
            return "false";
        }
    }

//    查看活动记录
    @RequestMapping("/getActivity")
    @ResponseBody
    public String getActivity(){
        System.out.println("活动+++++++++");
        List<Activity>  activityList = activityService.selectActivity();
        if (activityList != null ){
            String activitys = JSONObject.toJSONString(activityList);
            return activitys;
        }else {
            return "false";
        }
    }


    //发布动态
    @RequestMapping(value = "/adddynamic",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public String adddynamic(Dynamic dynamic){
        System.out.println("test----------------");
        System.out.println(dynamic);
        if (userService.addDynamic(dynamic)==1){
            return "success";
        }
        return "false";
    }

    //查询发布的动态
    @RequestMapping(value = "selectdynamic",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public  String  selectdynamic(){
        System.out.println("进入查询发布的动态");
        List<Dynamic> dynamic=userService.selectDynamic();
        String msg =JSONObject.toJSONString(dynamic);
        return msg;
    }

    //对评论进行评论
    @RequestMapping(value = "/addcomment",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public String addcomment(Comment comment){
        System.out.println("test----------------");
        System.out.println(comment);
        if (userService.addcomment(comment)==1){
            return "success";
        }
        return "false";
    }

    //查询对应对象的聊天记录
    @RequestMapping(value = "selectchat",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public String selectchat(Chat chat){
        System.out.println("进入查询发布的动态");
        List<Chat> chats=userService.selectChat(chat);
        String msg =JSONObject.toJSONString(chats);
        return msg;
    }


    //发送消息
    @RequestMapping(value = "/sendmessage",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public String sendmessage(Chat chat){
        chat.setChattime(Tool.getCurrentTime());
        System.out.println(Tool.getCurrentTime());
        System.out.println("发送消息");
        if (userService.sendmessage(chat)==1){
            return "success";
        }
        return "false";
    }


    //查询关注的对象列表
    @RequestMapping(value = "selectConcern",produces = "text/tml;charset=utf-8")
    @ResponseBody
    public String selectConcern(User user){
        System.out.println("查询关注列表");
        List<User> ulist=userService.selectConcern(user);
        String msg =JSONObject.toJSONString(ulist);
        return msg;
    }

    //磊--插入基本资料
    @RequestMapping("/basicmsg")
    @ResponseBody
    public String basicMessage(Userbasicmessage userbasicmessage) {
//        int uid = Integer.parseInt(cacheRedisService.get("uid"));
        System.out.println("用户基本信息填写-------------");
        System.out.println("传来的消息" + userbasicmessage);
        //登陆的用户
        int index = 0;
        if (userbasicmessage != null) {
            Userbasicmessage basic = userService.selectBasicMsg(21);
            //判断用户是否有填写信息，是的话执行修改，否执行插入
            userbasicmessage.setUid(21);
            if (basic == null) {
                System.out.println("插入基本资料表~~~~~~~~~~");

                index = userService.insertBasicMsg(userbasicmessage);
            } else {
                System.out.println("修改基本信息----------------");
                index = userService.uptBasicMsg(userbasicmessage);
            }
        }
        String msg = JSONObject.toJSONString(index);
        return msg;
    }


    //磊--插入详细资料
    @RequestMapping("/insertDetailMsg")
    @ResponseBody
    public String insertDetailMsg( Userdetailmessage userdetailmessage) {
//        int uid = Integer.parseInt(cacheRedisService.get("uid"));
        System.out.println("用户详细信息填写-------------");
        System.out.println("传来的消息" + userdetailmessage);

        int index = 0;
        if (userdetailmessage != null) {

            Userdetailmessage detail = userService.selectDetailMsg(21);

            //判断用户是否有填写信息，是的话执行修改，否执行插入
            if (detail == null) {
                System.out.println("插入详细信息表~~~~~~~~~~");
                userdetailmessage.setUid(21);
                index = userService.insertDetailMsg(userdetailmessage);
            } else {
                System.out.println("修改详细信息----------------");
                userdetailmessage.setUid(21);
                index = userService.uptDetailMsg(userdetailmessage);
            }
        }
        String msg = JSONObject.toJSONString(index);
        return msg;
    }


    //磊--插入择偶要求
    @RequestMapping("/insertLoverReq")
    @ResponseBody
    public String insertLoverReq(HttpSession httpSession, Userloverrequest userloverrequest, Userbasicmessage userbasicmessage) {
        System.out.println("用户择偶要求填写-------------");
        System.out.println("传来的消息" + userloverrequest);

        int index = 0;
        System.out.println("择偶对象***" + userloverrequest.getUsexrequest());
        if (userloverrequest != null) {
            if (userloverrequest.getUsexrequest().equals("男")) {
                System.out.println("择偶对象为男");
                userbasicmessage.setUid(21);
                userbasicmessage.setUlover("1");
                userService.uptBasicMsg(userbasicmessage);
            } else {
                System.out.println("择偶对象为女");
                userbasicmessage.setUid(21);
                userbasicmessage.setUlover("0");
                userService.uptBasicMsg(userbasicmessage);
            }

            Userloverrequest loverReq = userService.selectLoverReq(21);

            //判断用户是否有填写信息，是的话执行修改，否执行插入
            userloverrequest.setUid(21);
            if (loverReq == null) {
                System.out.println("插入择偶表~~~~~~~~~~");

                index = userService.insertLoverReq(userloverrequest);
            } else {
                System.out.println("修改择偶要求----------------");
                index = userService.uptLoverReq(userloverrequest);
            }
        }

        String msg = JSONObject.toJSONString(index);
        return msg;
    }

    //磊--查看基本资料
    @RequestMapping("/selectBasicMsg")
    @ResponseBody
    public String selectBasicMsg(String uid) {

        System.out.println("查看用户基本资料-------------"+uid);

        Userbasicmessage userbasicmessage = userService.selectBasicMsg(Integer.parseInt(uid));

        String msg = "";
        if (userbasicmessage!=null){
            System.out.println("打印用户基本信息--------" + userbasicmessage);
            msg = JSONObject.toJSONString(userbasicmessage);
        }else{

        }

        System.out.println("打印返回前端的信息" + msg);
        return msg;
    }

    //磊--查看详细资料
    @RequestMapping("/selectDetailMsg")
    @ResponseBody
    public String selectDetailMsg(HttpSession httpSession) {
        System.out.println("查看用户详细资料-------------");
        //登陆的用户
//        User user = (User) httpSession.getAttribute("user");
        Userdetailmessage userdetailmessage = userService.selectDetailMsg(21);
        System.out.println("打印用户详细信息--------" + userdetailmessage);
        String msg = JSONObject.toJSONString(userdetailmessage);
        System.out.println("打印返回前端的信息" + msg);
        return msg;

    }

    //磊--查看择偶资料
    @RequestMapping("/selectLoverReq")
    @ResponseBody
    public String selectLoverReq(HttpSession httpSession) {
        System.out.println("查看用户择偶要求-------------");
        //登陆的用户
//        User user = (User) httpSession.getAttribute("user");
        Userloverrequest userloverrequest = userService.selectLoverReq(21);

        //如果
        String msg = null;
        if (userloverrequest != null) {
            msg = JSONObject.toJSONString(userloverrequest);
        }

        System.out.println("打印择偶要求信息--------" + userloverrequest);

        System.out.println("打印返回前端的信息" + msg);
        return msg;
    }

    //磊--查看评价
    @RequestMapping("/selectEducate")
    @ResponseBody
    public String selectEducate(HttpSession httpSession) {
        System.out.println("查看用户评价-------------");
        //登陆的用户
//        User user = (User) httpSession.getAttribute("user");
        Userhobby userhobby = userService.selectEducate(21);
        System.out.println("打印评价--------" + userhobby);
        String msg = JSONObject.toJSONString(userhobby);
        System.out.println("打印返回前端的信息" + msg);
        return msg;
    }

    //磊--插入评价
    @RequestMapping("/insertEducate")
    @ResponseBody
    public String insertEducate(HttpSession httpSession, Userhobby userhobby) {
        System.out.println("插入自我评价----------");
        System.out.println("传来的消息" + userhobby);

        int index = 0;
        if (userhobby != null) {


            Userhobby hobby = userService.selectEducate(21);

            //判断用户是否有填写信息，是的话执行修改，否执行插入
            userhobby.setUid(21);
            if (hobby == null) {
                System.out.println("插入评价~~~~~~~~~~");

                index = userService.insertEducate(userhobby);
            } else {
                System.out.println("修改评价----------------");
                index = userService.uptEducate(userhobby);
            }
        }

        String msg = JSONObject.toJSONString(index);
        return msg;
    }



    //磊--充值
    @RequestMapping("/recharge")
    @ResponseBody
    public String recharge(HttpSession httpSession, Vipset vipset) {

        System.out.println("充值----------------");
        System.out.println("价格---------"+vipset.getVtype());

        //插入充值记录
        Recharge recharge = new Recharge();
        recharge.setUid(21);
        recharge.setRechargetype(0);
        recharge.setRechargemoney(vipset.getVtype());
        String date1 = Tool.getCurrentTime();
        System.out.println("时间-------"+date1);
        recharge.setRechargetime(date1);
        int index = vipsetService.insertVip(recharge);
//        //System.out.println("111111111::::"+cal.getTime());
//        cal.add(Calendar.YEAR, 1);//增加一年
//        //cd.add(Calendar.DATE, 1);//增加一天
//        //cd.add(Calendar.DATE, -10);//减10天
//        //cd.add(Calendar.MONTH, 1);//增加一个月
//        System.out.println("输出::"+cal.getTime());

        String msg = JSONObject.toJSONString(index);
        return msg;
    }



    @RequestMapping(value = "/redis",produces = "text/html;charset=utf-8")
    public String redis(){
        System.out.println("redis-----666-------=");
        cacheRedisService.add("redishello","123456");
        return "redis test";

    }

    @RequestMapping(value = "/httpSession",produces = "text/html;charset=utf-8")
    public String httpSession(String uacc,HttpSession httpSession){
        System.out.println("测试是否可以取到sessionVal----hghh------");
        String msg = "noname";
        if (cacheRedisService.get("userInfo") != null){
            msg = cacheRedisService.get("userInfo");
            System.out.println("redis---value++"+msg);
        }
        return msg;
    }

}
